package com.iuie.ns.frame.aop;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;

import com.iuie.ns.frame.exception.FileDownloadException;
import com.iuie.ns.frame.exception.ServiceException;
import com.iuie.ns.frame.web.response.vo.ResponseInfo;

/**
 * @desc 处理ServiceException的切面
 * @createTime 2017年6月25日 下午2:49:11
 * @author iuie
 */
@ControllerAdvice
public class ServiceExceptionHandler {
	
    // 指定要try catch的异常
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String handle(NativeWebRequest request, Exception e) {
        e.printStackTrace();
        
        String str = e.getMessage();
        // 普通业务异常
        if (e instanceof ServiceException) {
            ServiceException ex = (ServiceException) (e);
            String code = ex.getCode();
            Object info = ex.getInfo();
            return ResponseInfo.errorJson(str, code, info);
        }
        // 文件下载时异常
        if (e instanceof FileDownloadException) {
        	HttpServletResponse response = (HttpServletResponse) request.getNativeResponse();
            response.setContentType("application/json");
            response.setHeader("Content-Disposition", "inline;");
            
            FileDownloadException ex = (FileDownloadException) (e);
            String code = ex.getCode();
            Object info = ex.getInfo();
            String json = ResponseInfo.errorJson(str, code, info);
            String func = ex.getFunc();
            
            String jsJson = StringEscapeUtils.escapeJavaScript(json);
    		String html = "<script type='text/javascript'>var obj = JSON.parse('" + jsJson + "');parent." + func + "(obj);</script>";
    		return html;
        }
        return ResponseInfo.errorJson(e.getMessage());
    }

}
